package framework;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * Title: framework.ConsumerProxy<br/>
 * Description: 服务消费代理接口<br/>
 * version: 1.0<br/>
 *
 * @author : hzg<br/>
 * date: 2021/9/13 14:59<br/>
 */
public class ConsumerProxy {
    public static <T> T consume(final Class<T> interfaceClass, final String host,final int port) throws Exception{
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class<?>[]{interfaceClass}, (InvocationHandler) (proxy, method, args) -> {
            Socket socket = new Socket(host,port);
            try {
                ObjectOutputStream output = new ObjectOutputStream(socket.getOutputStream());
                try {
                    output.writeUTF(method.getName());
                    output.writeObject(args);
                    ObjectInputStream input = new ObjectInputStream(
                            socket.getInputStream()
                    );
                    try {
                        Object result = input.readObject();
                        if (result instanceof Throwable){
                            throw (Throwable) result;
                        }
                        return result;
                    }finally {
                        input.close();
                    }
                }finally {
                    output.close();
                }
            }finally {
                socket.close();
            }
        });
    }
}
